/*
 * @Author: yangzonglong
 * @Date: 2021-02-25 14:35:42
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: TLL
 * @LastEditTime: 2021-05-06 10:56:40
 * @Auditor: 
 */
import React, { memo, useCallback, useMemo } from 'react';
import { FormItemProps, Extra } from './interface';
import { ControlMap, FormxControlTypes } from './data';
import { handleRowColStyle, getPlaceholder } from './util';
import { Form, Col } from 'antd';
import { Icon } from '@library';

interface IProps {
  formItem: FormItemProps;
  disabled: boolean;
  rules: any[];
  groupNumber?: number;
  id?: string;
  placeholder?: string;
  extra?: Extra;
  extraInitialValue?: any
}

const FormItem = ({ formItem, id, groupNumber, disabled, rules, extra, extraInitialValue }: IProps) => {

  const Control: any = ControlMap[formItem.type!] || ControlMap[FormxControlTypes.INPUT];
  const vName = formItem.type === 'switch' ? 'checked' : 'value';

  const rowColStyle = useMemo(() => {
    return formItem.span ? { span: formItem.span } : handleRowColStyle(groupNumber)
  }, [groupNumber, formItem.span])

  const curExtra = useMemo(() => extra?.find(item => item.name === id), [extra]);
  const label = formItem.label || window.$app.t(formItem.name);
  const suffixIcon = formItem.type === FormxControlTypes.RANGE_PICKER ? {suffixIcon: <Icon icon="&#xe62d;" />} : null;
 
  return (
    <Col span={rowColStyle.span}>
      <Form.Item name={formItem.name} rules={rules} valuePropName={vName} label={label} >
        {curExtra ? curExtra.render({ id: id as string, placeholder: getPlaceholder(formItem) }) : (
          <Control 
            id={id} 
            disabled={disabled} 
            {...formItem.options} 
            required={formItem.required}
            extraInitialValue={extraInitialValue}
            placeholder={disabled ?  "-" : getPlaceholder(formItem) || undefined}
            {...suffixIcon}
          />
        )}
      </Form.Item>
    </Col>
  )
}

function equal(prevProps: IProps, nextProps: IProps) {
  return prevProps.formItem === nextProps.formItem
    && prevProps.disabled === nextProps.disabled
    && prevProps.rules === nextProps.rules
    && prevProps.extra === nextProps.extra
    && prevProps.extraInitialValue === nextProps.extraInitialValue
}

export default memo(FormItem, equal)